package com.sj.controller;


import com.sj.common.lang.ApiResultMsg;
import com.sj.common.lang.ResultInfo;
import com.sj.entity.Comment;
import com.sj.service.CommentService;
import com.sj.utils.MineUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 小七
 * @since 2021-07-30
 */
@Api(tags = "评论模块")
@RestController
@RequestMapping("/api/comment")
public class CommentController extends BaseController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private MineUtils mineUtils;

    @PutMapping("/save")
    @ApiOperation(value = "发布评论接口")
    public ApiResultMsg<Comment> save(@RequestBody @Validated Comment comment) {
        boolean result = commentService.save(comment);
        if (result) {
            return ApiResultMsg.success("评论成功");
        }
        return ApiResultMsg.error("评论失败");
    }

    @GetMapping("/list/{blogId}")
    @ApiOperation(value = "获取博客评论")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "blogId", value = "博客id"),
    })
    public ApiResultMsg<Comment> listComment(@PathVariable(value = "blogId") Integer blogId) {
        // 只拿到最高一级的评论
        List<Comment> list = commentService.listCommentWhereParentIdIsNull(blogId);
        getCommentChildList(list);

        return ApiResultMsg.success(ResultInfo.SUCCESS, list);
    }

    private List<Comment> allReplyCommentList = new ArrayList<Comment>();

    private void getCommentChildList(List<Comment> list) {

        if (list != null && list.size() > 0) {
            // 遍历所有一级评论，找到回复该评论的所有评论
            list.forEach(item -> {
                List<Comment> childList = commentService.getCommentByParentId(item.getId());
                loadChildren(childList);
                item.setChildCommentList(allReplyCommentList);
                allReplyCommentList = new ArrayList<Comment>();
            });
        }
    }

    private void loadChildren(List<Comment> childList) {
        if (childList != null && childList.size() > 0) {
            allReplyCommentList = mineUtils.concatList(allReplyCommentList, childList);
            childList.forEach(item -> {
                List<Comment> list = commentService.getCommentByParentId(item.getId());
                loadChildren(list);
            });
        }
    }

}

